package org.ldh.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用于创建数据库连接的工厂
 */
public class ConnectionFactory {
    //获取数据源 自动读取c3p0-config.xml文件
    private static DataSource dataSource = new ComboPooledDataSource();

    //获取连接
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //释放资源
    public static void close(Connection conn, PreparedStatement pstm, ResultSet rs) {
        try{
            if(rs != null){
                rs.close();
            }
            if(pstm != null){
                pstm.close();
            }
            if(conn != null){
                pstm.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //释放资源
    public static void close(Connection conn, PreparedStatement pstm) {
        try{
            if(pstm != null){
                pstm.close();
            }
            if(conn != null){
                pstm.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
